<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use Hash;
use Session;
class LoginController extends Controller
{
    //执行登录
    public function login(Request $request)
    {
    	if($request -> isMethod('post'))
    	{
    		$this -> validate($request,[
    			'email' => 'required',
    			'password' => 'required',
    			'captcha' => 'required',
    			],[
    			'email.required' => '邮箱不能为空',
    			'password.required' => '密码不能为空',
    			'captcha.required' => '验证码不能为空',
    			]);
    		$data = $request -> except('_token');
    		$c = Session::get('milkcaptcha');
    		if($c != $data['captcha'])
    		{
    			$request -> flash();
    			return back() -> with(['info' => '验证码错误']);
    		}

    		$res = DB::table('users') -> where('email',$data['email']) -> first();
    		if(!$res)
    		{
    			return back() -> with(['info' => '用户名或密码错误']);
    		}

    		$r = Hash::check($data['password'],$res -> password);

    		if(!$r)
    		{
    			return back() -> with(['info' => '用户名或密码错误']);
    		}
    		Session::set('master',$res);
    		return redirect('/admin/index') -> with(['info' => '登录成功']);
    	}
    	return view('admin.login');
    }

    //退出登录
    public function logout()
    {
    	Session::forget('master');
    	return redirect('/admin/login') -> with(['info' => '退出成功']);
    }
}
